﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPFClient.Codes;

namespace WPFClient.Views
{
    /// <summary>
    /// TestView.xaml 的交互逻辑
    /// </summary>
    public partial class TestView : UserControl
    {
        private const int MAX_LINES = 200;

        public TestView()
        {
            InitializeComponent();
            Connect();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        public async void Connect()
        {
            try
            {
                TCPHelper tpcHelper = new TCPHelper(ConfigHelper.GetConfigValue("$.PLCMachine.PLC1.IP"), ConfigHelper.GetConfigValue("$.PLCMachine.PLC1.Port"));
                await tpcHelper.Connect((datas, dataGridLength) => {
                    if (dataGridLength > 0)
                    {
                        // 将接收到的数据转换为字符串
                        string receivedData = Encoding.UTF8.GetString(datas, 0, dataGridLength);

                        // 在UI线程上更新接收文本框
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            RollerPLCProtocolMessage data = RollerPLCDataLogic.RollerPLCDataParse(datas);
                            MessageBox.Show($"收到数据: {data.DeviceId}");
                        }));
                    }
                });
            }
            catch (SocketException ex)
            {
                UpdateMessage($"连接错误: {ex.Message}", Colors.Red);
            }
            catch (Exception ex)
            {
                UpdateMessage($"错误: {ex.Message}", Colors.Red);
            }
        }

        /// <summary>
        /// 在消息文本框显示信息（带颜色）
        /// </summary>
        private void UpdateMessage(string message, Color color)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                tbMsg.Text = message;
                tbMsg.Foreground = new SolidColorBrush(color);
            }));
        }

        /// <summary>
        /// 在接收文本框追加数据
        /// </summary>
        private void AppendReceivedData(string data)
        {
            // 添加时间戳
            string timestamp = DateTime.Now.ToString("HH:mm:ss");
            string formattedData = $"[{timestamp}] {data}";

            // 追加新数据
            tbReceive.AppendText(formattedData + Environment.NewLine);

            // 限制最大行数
            var lines = tbReceive.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            if (lines.Length > MAX_LINES)
            {
                tbReceive.Text = string.Join(Environment.NewLine, lines.Skip(lines.Length - MAX_LINES));
            }

            // 滚动到最后
            tbReceive.ScrollToEnd();
        }

        private void btnChangeLanguage_Click(object sender, RoutedEventArgs e)
        {
            if (GlobalObject.CurrentLanguageManager.CurrentLanguageFileName == LanguageManager.Chinese)
                GlobalObject.CurrentLanguageManager.SetLanguage(LanguageManager.English);
            else
                GlobalObject.CurrentLanguageManager.SetLanguage(LanguageManager.Chinese);
        }
    }
}
